<?php
//https://packagist.org/packages/guzzlehttp/guzzle
//https://docs.guzzlephp.org/en/stable/quickstart.html
require 'vendor/autoload.php';

//use GuzzleHttp\Client;
//use GuzzleHttp\Promise;

/*
$start = microtime(true);
echo "Fetching..." . PHP_EOL;

$client = new Client();

// 创建多个请求，请求地址可以相同，也可以不同
$promises = [];

foreach (range(1, 20) as $k => $v) {
    $promises[$k] = $client->getAsync('http://127.0.0.1:9501/test/slow_api?r=' . $v);
}

// 发送并发请求，并等待所有请求完成（每个请求之间是异步的，因此效率非常高），返回一个响应数组
$responses = Promise\Utils::unwrap($promises);

// 处理响应
foreach ($responses as $k => $response) {
    $result = $response->getBody()->getContents();
    echo $k . ' : ' . $result . PHP_EOL;
    // $result即接口返回的body体，{code:0,message:ok,data:{}}，可以使用json_decode转一下
}

echo "...done in " . (microtime(true) - $start) . PHP_EOL;
*/

use GuzzleHttp\Client;
use GuzzleHttp\Exception\RequestException;
use GuzzleHttp\Pool;
use GuzzleHttp\Psr7\Request;
use GuzzleHttp\Psr7\Response;

$start = microtime(true);
echo "Fetching..." . PHP_EOL;
$client = new Client();

$requests = function ($total) {
    $uri = 'http://127.0.0.1:9501/test/slow_api?r=';
    for ($i = 0; $i < $total; $i++) {
        yield new Request('GET', $uri . $i);
    }
};

$pool = new Pool($client, $requests(100), [
    'concurrency' => 50,
    'fulfilled' => function (Response $response, $index) {
        // this is delivered each successful response
        echo $response->getBody();
        echo PHP_EOL;
    },
    'rejected' => function (RequestException $reason, $index) {
        // this is delivered each failed request
    },
]);

// Initiate the transfers and create a promise
$promise = $pool->promise();

// Force the pool of requests to complete.
$promise->wait();

echo "...done in " . (microtime(true) - $start) . PHP_EOL;